package com.weavernorth.retailExperienceAward.service;

import com.weavernorth.util.dateUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.workflow.webservices.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.retailExperienceAward.service
 * @date: 2022/2/14 16:26
 * @description: 定时任务：自动触发hr评分流程
 */
public class ZhrScorePlanService {
    public Logger log;

    public Logger getLog() {
        return log;
    }

    public void setLog(Logger log) {
        this.log = log;
    }

    public void createFormal() {
        RecordSet rs = new RecordSet();
        RecordSet rs_flow = new RecordSet();
        RecordSet rs_hr = new RecordSet();
        RecordSet rs_detail1 = null;
        RecordSet rs_detail2 = null;
        //基础类
        BaseBean bb = new BaseBean();
        String strCreator = "1";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String strJcrq = df.format(new Date());
        String strKhzq = dateUtils.previousMonth(0);
        log.info("考核周期为：" + strKhzq);
        //配置流程基本信息:workflowId
        WorkflowBaseInfo wbi = new WorkflowBaseInfo();
        //获取workflowid,添加配置文件，配置流程id
        String strSql1 = "SELECT id FROM workflow_base WHERE WORKFLOWNAME LIKE'%HR评分流程%'";
        rs_flow.execute(strSql1);
        String workflowid = "0";
        while (rs_flow.next()) {
            workflowid = Util.null2String(rs_flow.getString("id"));
        }
        log.info("workflowid的值：" + workflowid);
        wbi.setWorkflowId(workflowid);
        //获取主表,添加配置文件，配置流程id
        String strGetTable = "select tablename  from workflow_bill where id = (select formid from workflow_base where id=" + workflowid + " and isbill=1)";
        rs.execute(strGetTable);
        String strTable = "";
        while (rs.next()) {
            strTable = Util.null2String(rs.getString("tablename"));
        }
        log.info("流程表名：" + strTable);

        JSONArray jsonArray = null;
        JSONArray jsonArray2 = null;
        JSONObject jsObj = null;
        JSONObject jsObj2 = null;
        String strGetHr = "SELECT TO_CHAR(a.hr) hr FROM uf_dpxx a LEFT JOIN hrmdepartment b ON  a.DP=b.ID INNER JOIN uf_cfdplstykh c ON a.fgs=c.fgsppdy  WHERE a.dpjb IN(2,3,4) and a.dpzt=0 AND a.QYJL is NOT NULL and a.dp is not null GROUP BY TO_CHAR(a.hr)";
        rs_hr.executeQuery(strGetHr);
        log.info("获取hr的sql：" + strGetHr);
        try {
            while (rs_hr.next()) {
                jsonArray = new JSONArray();
                rs_detail1 = new RecordSet();
                jsonArray2 = new JSONArray();
                rs_detail2 = new RecordSet();
                String strHr = Util.null2String(rs_hr.getString("hr"));
                //region [明细表1(店铺人员)]
                String strSql = "SELECT a.fgs,a.dpsapid,TO_CHAR(a.hr) hr,a.ppkdx,a.dp,a.dpjb,a.dpzt,b.departmentname FROM uf_dpxx a LEFT JOIN hrmdepartment b ON  a.DP=b.ID INNER JOIN uf_cfdplstykh c ON a.fgs=c.fgsppdy WHERE  a.dpjb IN(0,1,2,3,4) and a.dpzt=0 and TO_CHAR(a.hr)='" + strHr + "' AND a.dp is NOT NULL " +
                        " AND EXISTS(SELECT f.departmentid FROM hrmresource f WHERE f.departmentid=a.DP) " +
                        " AND NOT EXISTS(SELECT * FROM uf_yddpzxygxxd h WHERE a.FGS=h.fgs AND a.DP=h.dp AND h.khzq='" + strKhzq + "')" +
                        " AND NOT EXISTS(SELECT d.FGS,d.sapid,d.dp FROM " + strTable + "_dt1 d WHERE a.FGS=d.fgs AND a.DP=d.dp and d.khzq='" + strKhzq + "' )" +
                        " ORDER BY a.fgs,a.dp asc";
                log.info("hr负责评分的店铺sql：" + strSql);

                rs_detail1.execute(strSql);
                while (rs_detail1.next()) {
                    jsObj = new JSONObject();
                    //分公司
                    jsObj.put("fgs", Util.null2String(rs_detail1.getString("fgs")));
                    //店铺
                    String strDpId = Util.null2String(rs_detail1.getString("dp"));
                    jsObj.put("dp", strDpId);
                    log.info("店铺ID：" + strDpId);
                    //店铺SAPID
                    String strSAPID = Util.null2String(rs_detail1.getString("dpsapid"));
                    jsObj.put("sapid", strSAPID);
                    log.info("店铺SAPID：" + strSAPID);
                    jsonArray.add(jsObj);

                }
                //endregion

                //region [明细表2(区域经理)]
                String strSql2 = "SELECT a.fgs,TO_CHAR(a.qyjl) qyjl,h.workcode gh,TO_CHAR(a.hr) hr FROM uf_dpxx a INNER JOIN HRMRESOURCE h ON TO_CHAR(a.qyjl)=h.id\n" +
                        "\tWHERE a.fgs IS NOT NULL  AND a.qyjl IS NOT NULL  AND a.dpzt=0 AND a.hr is not NULL and a.dp is not null and TO_CHAR(a.hr)='" + strHr + "'\n" +
                        "\tGROUP BY a.fgs, TO_CHAR(a.qyjl),TO_CHAR(a.hr),h.workcode";
                log.info("hr负责评分的区域经理sql：" + strSql2);
                rs_detail2.execute(strSql2);
                while (rs_detail2.next()) {
                    jsObj2 = new JSONObject();
                    //分公司
                    jsObj2.put("fgs", Util.null2String(rs_detail2.getString("fgs")));
                    //区域经理id
                    String strXm = Util.null2String(rs_detail2.getString("qyjl"));
                    jsObj2.put("xm", strXm);
                    log.info("区域经理id：" + strXm);
                    //区域经理工号
                    String strGh = Util.null2String(rs_detail2.getString("gh"));
                    jsObj2.put("gh", strGh);
                    log.info("区域经理工号：" + strGh);
                    jsonArray2.add(jsObj2);
                }
                //endregion

                WorkflowRequestTableField[] wrMain = new WorkflowRequestTableField[2];
                log.info("评分人字段赋值：");
                wrMain[0] = new WorkflowRequestTableField();
                wrMain[0].setFieldName("pfr");
                wrMain[0].setFieldValue(strHr);
                wrMain[0].setView(true);
                wrMain[0].setEdit(true);
                wrMain[0].setFieldOrder(0);
                wrMain[0].setMand(false);

                //创建时间
                log.info("考核周期：");
                wrMain[1] = new WorkflowRequestTableField();
                wrMain[1].setFieldName("khzq");
                wrMain[1].setFieldValue(strKhzq);
                wrMain[1].setView(true);
                wrMain[1].setEdit(true);
                wrMain[1].setFieldOrder(0);
                wrMain[1].setMand(false);
                //填装主表信息
                WorkflowRequestTableRecord[] wrtri = new WorkflowRequestTableRecord[1];
                wrtri[0] = new WorkflowRequestTableRecord();
                wrtri[0].setWorkflowRequestTableFields(wrMain);
                WorkflowMainTableInfo wmi = new WorkflowMainTableInfo();
                wmi.setRequestRecords(wrtri);

                WorkflowRequestInfo wrInfo = new WorkflowRequestInfo();
                wrInfo.setCreatorId("01");
                wrInfo.setRequestLevel("0");//紧急程度
                wrInfo.setRequestName("【品牌】 HR评分流程");//请求的名称
                //停留在提交节点
                wrInfo.setIsnextflow("1");
                //主表数据
                wrInfo.setWorkflowMainTableInfo(wmi);
                wrInfo.setWorkflowBaseInfo(wbi);
                //明细表
                WorkflowDetailTableInfo wdti[] = new WorkflowDetailTableInfo[2];
                //明细表1
                if (jsonArray.size() > 0) {
                    log.info("数组长度："+jsonArray.size());
                    wrtri = getDetail1(jsonArray, strKhzq);
                    wdti[0] = new WorkflowDetailTableInfo();
                    wdti[0].setWorkflowRequestTableRecords(wrtri);
                }
                if (jsonArray2.size() > 0) {
                    log.info("数组长度："+jsonArray2.size());
                    wrtri = getDetail2(jsonArray2, strKhzq);
                    wdti[1] = new WorkflowDetailTableInfo();
                    wdti[1].setWorkflowRequestTableRecords(wrtri);
                }
                wrInfo.setWorkflowDetailTableInfos(wdti);
                wrInfo.setCreatorId(strHr);
                WorkflowServiceImpl wfsi_bcd = new WorkflowServiceImpl();
                String requestid = wfsi_bcd.doCreateWorkflowRequest(wrInfo, Integer.parseInt(strHr));
                log.info("HR评分流程-批量生成流程返回值==" + requestid);
                if (!"".equals(requestid) && Integer.parseInt(requestid) > 0) {
                    log.info("HR评分流程创建成功！");
                } else {
                    log.info("HR评分流程创建失败！");
                }
                jsonArray.clear();
                jsonArray2.clear();
            }
        } catch (Exception ex) {
            jsonArray.clear();
            jsonArray2.clear();
            log.info("程序执行异常，异常信息：" + ex.toString());
        }
    }

    /**
     * 封装明细表1数据
     */

    public WorkflowRequestTableRecord[] getDetail1(JSONArray jsonArray, String strKhzq) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String strJcrq = df.format(new Date());
        WorkflowRequestTableRecord[] wrtri = new WorkflowRequestTableRecord[jsonArray.size()];
        WorkflowRequestTableField[] wrti;
        for (int i = 0; i < jsonArray.size(); i++) {

            JSONObject jsonObject = jsonArray.getJSONObject(i);
            log.info("封装明细1json:" + jsonObject);
            try {
                wrti = new WorkflowRequestTableField[5];
                wrti[0] = new WorkflowRequestTableField();
                wrti[0].setFieldName("fgs");
                wrti[0].setFieldValue(jsonObject.getString("fgs"));
                wrti[0].setView(true);
                wrti[0].setEdit(true);

                wrti[1] = new WorkflowRequestTableField();
                wrti[1].setFieldName("dp");
                wrti[1].setFieldValue(jsonObject.getString("dp"));
                wrti[1].setView(true);
                wrti[1].setEdit(true);

                wrti[2] = new WorkflowRequestTableField();
                wrti[2].setFieldName("sapid");
                wrti[2].setFieldValue(jsonObject.getString("sapid"));
                wrti[2].setView(true);
                wrti[2].setEdit(true);

                wrti[3] = new WorkflowRequestTableField();
                wrti[3].setFieldName("khrq");
                wrti[3].setFieldValue(strJcrq);
                wrti[3].setView(true);
                wrti[3].setEdit(true);

                wrti[4] = new WorkflowRequestTableField();
                wrti[4].setFieldName("khzq");
                wrti[4].setFieldValue(strKhzq);
                wrti[4].setView(true);
                wrti[4].setEdit(true);

                wrtri[i] = new WorkflowRequestTableRecord();
                wrtri[i].setWorkflowRequestTableFields(wrti);
            } catch (Exception ex) {
                log.info("封装明细表1数据出现异常,异常信息：" + ex.toString());
            }


        }
        return wrtri;
    }

    /**
     * 封装明细表2数据
     */

    public WorkflowRequestTableRecord[] getDetail2(JSONArray jsonArray, String strKhzq) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String strJcrq = df.format(new Date());
        WorkflowRequestTableRecord[] wrtri = new WorkflowRequestTableRecord[jsonArray.size()];
        WorkflowRequestTableField[] wrti;
        for (int i = 0; i < jsonArray.size(); i++) {

            JSONObject jsonObject = jsonArray.getJSONObject(i);
            log.info("封装明细2json:" + jsonObject);
            try {
                wrti = new WorkflowRequestTableField[3];
                wrti[0] = new WorkflowRequestTableField();
                wrti[0].setFieldName("fgs");
                wrti[0].setFieldValue(jsonObject.getString("fgs"));
                wrti[0].setView(true);
                wrti[0].setEdit(true);

                wrti[1] = new WorkflowRequestTableField();
                wrti[1].setFieldName("xm");
                wrti[1].setFieldValue(jsonObject.getString("xm"));
                wrti[1].setView(true);
                wrti[1].setEdit(true);

                wrti[2] = new WorkflowRequestTableField();
                wrti[2].setFieldName("gh");
                wrti[2].setFieldValue(jsonObject.getString("gh"));
                wrti[2].setView(true);
                wrti[2].setEdit(true);

                wrtri[i] = new WorkflowRequestTableRecord();
                wrtri[i].setWorkflowRequestTableFields(wrti);
            } catch (Exception ex) {
                log.info("封装明细表2数据出现异常,异常信息：" + ex.toString());
            }
        }
        return wrtri;
    }

}
